package org.example.SolutionNew002;

public class LinkedList10 {
    public static void main(String[] args) {
        LinkedList10 list=new LinkedList10();
        ListNode head1 = new ListNode(1);
        head1.next = new ListNode(2);
        head1.next.next = new ListNode(3);
        head1.next.next.next = new ListNode(4);
        head1.next.next.next.next = new ListNode(5);
        ListNode res=list.reverseKGroup(head1,5);
        while(res!=null){
            System.out.println(res.val);
            res=res.next;
        }
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if(head==null||head.next==null||k==1) return head;
        ListNode dummy=new ListNode(0);
        dummy.next=head;
        int count=0;
        ListNode prev=dummy;
        ListNode pro=dummy;
        while(pro!=null){
            if(count==k){
                ListNode temp2=prev.next;
                //翻转链表prev.next~pro
                reverseList(prev,pro);
                prev=temp2;
                pro=temp2;
                count=0;
            }
            pro=pro.next;
            count++;
        }
        return dummy.next;
    }

    public void reverseList(ListNode head,ListNode pro){
        while(head.next!=pro){
            ListNode temp=head.next;
            head.next=temp.next;
            temp.next=pro.next;
            pro.next=temp;
        }
    }
}
